package cn.iocoder.yudao.module.erp.service.business.order.orderaddress;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.business.order.orderaddress.vo.OrderAddressPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.business.order.orderaddress.vo.OrderAddressSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.business.order.orderaddress.OrderAddressDO;
import cn.iocoder.yudao.module.erp.dal.mysql.business.order.orderaddress.OrderAddressMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.ORDER_ADDRESS_NOT_EXISTS;

/**
 * 交付地址 Service 实现类
 *
 * @author yy
 */
@Service
@Validated
public class OrderAddressServiceImpl implements OrderAddressService {

    @Resource
    private OrderAddressMapper orderAddressMapper;

    @Override
    public Long createOrderAddress(OrderAddressSaveReqVO createReqVO) {
        // 插入
        OrderAddressDO orderAddress = BeanUtils.toBean(createReqVO, OrderAddressDO.class);
        //判断常用唯一
        List<OrderAddressDO> list = orderAddressMapper.selectList();
        if(list.size() == 0)
            orderAddress.setStatus(true);
        orderAddressMapper.insert(orderAddress);
        // 返回
        return orderAddress.getId();
    }

    @Override
    public void updateOrderAddress(OrderAddressSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderAddressExists(updateReqVO.getId());
        // 更新
        OrderAddressDO updateObj = BeanUtils.toBean(updateReqVO, OrderAddressDO.class);
        //判断常用唯一
        if(updateObj.getStatus()){
            List<OrderAddressDO> list = orderAddressMapper.selectList();
            list.forEach( item -> {
                if(item.getStatus()){
                    item.setStatus(false);
                    orderAddressMapper.updateById(item);
                }
            });
        }
        orderAddressMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderAddress(Long id) {
        // 校验存在
        validateOrderAddressExists(id);
        // 删除
        orderAddressMapper.deleteById(id);
    }

    private void validateOrderAddressExists(Long id) {
        if (orderAddressMapper.selectById(id) == null) {
            throw exception(ORDER_ADDRESS_NOT_EXISTS);
        }
    }

    @Override
    public OrderAddressDO getOrderAddress(Long id) {
        return orderAddressMapper.selectById(id);
    }

    @Override
    public PageResult<OrderAddressDO> getOrderAddressPage(OrderAddressPageReqVO pageReqVO) {
        return orderAddressMapper.selectPage(pageReqVO);
    }

}